import React, { useState, useEffect } from "react";
import { Eye, Menu, ChevronRight, Code, FileText, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

import { ProjectAPI } from "@/api/project";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import MarkdownPreviewRenderer from "./MarkdownPreviewRenderer"; // **核心：导入新的渲染器**
import CollapsibleToc from "./CollapsibleToc";

export default function DocumentTemplatePreview({
  template,
  onClose,
  isFullscreen,
  onToggleFullscreen,
}) {
  const [showToc, setShowToc] = useState(true);
  const [activeSection, setActiveSection] = useState(null);
  const [viewMode, setViewMode] = useState("rendered"); // "rendered" 或 "source"

  const [schemes, setSchemes] = useState([]);
  const [selectedSchemeId, setSelectedSchemeId] = useState("");
  const [previewData, setPreviewData] = useState(null);
  const [isLoadingData, setIsLoadingData] = useState(false);

  useEffect(() => {
    loadSchemes();
  }, []);

  const loadSchemes = async () => {
    try {
      const schemesData = await ConstructionSchemeAPI.getList({
        sort: "-created_date",
      });
      setSchemes(schemesData.data || []);
    } catch (error) {
      console.error("加载施工方案失败:", error);
    }
  };

  const loadPreviewData = async (schemeId) => {
    if (!schemeId) {
      setPreviewData(null);
      return;
    }
    setIsLoadingData(true);
    try {
      const scheme = await ConstructionSchemeAPI.get(schemeId);
      const crossingPoint = scheme?.crossingPointId
        ? await CrossingPointAPI.getDetail(scheme.crossingPointId).catch(
            () => null
          )
        : null;
      const project = crossingPoint?.projectId
        ? await ProjectAPI.get(crossingPoint.projectId).catch(() => null)
        : null;

      const flatData = {};
      const sources = {
        project,
        crossing: crossingPoint,
        scheme,
        system: {
          current_date: new Date().toLocaleDateString("zh-CN"),
          generator: "模板预览系统",
        },
      };

      for (const prefix in sources) {
        if (sources[prefix]) {
          for (const key in sources[prefix]) {
            const newKey = `${prefix}_${key}`;
            flatData[newKey] =
              sources[prefix][key] !== null &&
              sources[prefix][key] !== undefined
                ? sources[prefix][key]
                : "未设定";
          }
        }
      }
      setPreviewData(flatData);
    } catch (error) {
      console.error("加载预览数据失败:", error);
      alert("加载预览数据失败: " + error.message);
      setPreviewData(null);
    } finally {
      setIsLoadingData(false);
    }
  };

  const replaceVariables = (content, data) => {
    if (!data || !content) return content || "";
    let result = content;
    const arrayPattern = /\{\{#([\w_]+)\}\}([\s\S]*?)\{\{\/\1\}\}/g;

    result = result.replace(arrayPattern, (match, arrayName, template) => {
      const arrayData = data[arrayName];
      if (!Array.isArray(arrayData) || arrayData.length === 0) {
        return "- 暂无数据";
      }
      return arrayData
        .map((item) => {
          let itemResult = template;
          if (typeof item === "object" && item !== null) {
            for (const [key, value] of Object.entries(item)) {
              itemResult = itemResult.replace(
                new RegExp(`\\{\\{${key}\\}\\}`, "g"),
                String(value || "")
              );
            }
          } else {
            itemResult = itemResult.replace(/\{\{\.\}\}/g, String(item || ""));
          }
          return itemResult;
        })
        .join("");
    });

    for (const [key, value] of Object.entries(data)) {
      if (typeof value !== "object" || value === null) {
        result = result.replace(
          new RegExp(`\\{\\{${key}\\}\\}`, "g"),
          String(value || "")
        );
      }
    }
    return result;
  };

  const getMarkdownContent = () => {
    const rawMarkdown = template.templateContent?.markdown || "暂无内容";
    if (previewData) {
      return replaceVariables(rawMarkdown, previewData);
    }
    return rawMarkdown;
  };

  const markdownContent = getMarkdownContent();

  const generateTableOfContents = (content) => {
    const headings = [];
    const lines = content.split("\n");

    lines.forEach((line, index) => {
      const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
      if (headingMatch) {
        const level = headingMatch[1].length;
        const title = headingMatch[2];
        const id = `heading-${index}`;
        headings.push({ id, title, level });
      }
    });

    return headings;
  };

  const toc = generateTableOfContents(markdownContent);

  const scrollToSection = (sectionId) => {
    const container = document.getElementById("preview-scroll-container");
    const element = document.getElementById(sectionId);
    if (element && container) {
      container.scrollTo({
        top: element.offsetTop - 20, // 20px offset
        behavior: "smooth",
      });
      setActiveSection(sectionId);
    }
  };

  return (
    <div className="h-full flex flex-col">
      {/* Header */}
      <div className="flex-shrink-0 border-b bg-gray-50 p-4">
        <div className="flex items-center justify-between gap-4">
          <div className="flex-1 min-w-0">
            <h2
              className="text-lg font-semibold truncate"
              title={template.name}
            >
              {template.name}
            </h2>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            <Tabs
              value={viewMode}
              onValueChange={setViewMode}
              className="w-auto"
            >
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger
                  value="rendered"
                  className="flex items-center gap-1"
                >
                  <Eye className="w-4 h-4 mr-1" />
                  预览
                </TabsTrigger>
                <TabsTrigger value="source" className="flex items-center gap-1">
                  <Code className="w-4 h-4 mr-1" />
                  源码
                </TabsTrigger>
              </TabsList>
            </Tabs>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowToc(!showToc)}
              className="flex items-center gap-2"
            >
              <Menu className="w-4 h-4" />
              {showToc ? "隐藏" : "显示"}目录
            </Button>
            {onToggleFullscreen && (
              <Button variant="outline" size="sm" onClick={onToggleFullscreen}>
                {isFullscreen ? "退出全屏" : "全屏预览"}
              </Button>
            )}
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-xl font-bold p-1"
            >
              ×
            </button>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 min-h-0 flex">
        {/* Table of Contents */}
        {showToc && (
          <div className="w-64 border-r bg-gray-50 flex flex-col">
            <div className="p-4 border-b">
              <h3 className="font-medium text-gray-800">目录导航</h3>
            </div>
            {/* 核心修改：使用新的可折叠目录组件 */}
            <div className="space-y-1 overflow-y-auto p-2 flex-1">
              <CollapsibleToc
                content={markdownContent}
                onSectionClick={scrollToSection}
              />
            </div>
          </div>
        )}

        {/* Document Preview */}
        <div
          id="preview-scroll-container"
          className="flex-1 overflow-y-auto p-6 min-h-0"
        >
          <div className="max-w-4xl mx-auto">
            {/* 数据选择器 */}
            <div className="mb-6 p-4 border rounded-lg bg-white shadow-sm">
              <Label
                htmlFor="scheme-selector"
                className="font-semibold text-gray-800"
              >
                选择一个真实施工方案代入变量预览
              </Label>
              <div className="flex items-center gap-2 mt-2">
                <Select
                  value={selectedSchemeId || ""}
                  onValueChange={(v) => {
                    setSelectedSchemeId(v);
                    loadPreviewData(v);
                  }}
                >
                  <SelectTrigger id="scheme-selector">
                    <SelectValue placeholder="选择方案..." />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={null}>
                      不代入数据（显示变量名）
                    </SelectItem>
                    {schemes.map((s) => (
                      <SelectItem key={s.id} value={s.id}>
                        {s.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {isLoadingData && (
                  <Loader2 className="w-5 h-5 animate-spin text-blue-600" />
                )}
              </div>
            </div>

            <Tabs value={viewMode} onValueChange={setViewMode}>
              <TabsContent value="rendered" className="mt-0">
                <div className="bg-white border shadow p-8 rounded-lg">
                  {/* **核心：使用新的、更强大的渲染器** */}
                  <MarkdownPreviewRenderer content={markdownContent} />
                </div>
              </TabsContent>

              <TabsContent value="source" className="mt-0">
                <div className="bg-gray-900 text-gray-100 p-6 rounded-lg">
                  <pre className="whitespace-pre-wrap text-sm font-mono overflow-x-auto">
                    {markdownContent || "暂无内容"}
                  </pre>
                </div>
              </TabsContent>
            </Tabs>
          </div>
        </div>
      </div>
    </div>
  );
}
